﻿using Groove.Core.MediaFile;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace Groove.Winform.Playlist
{
    public partial class UcPlaylistItem : UserControl
    {
        private bool _isPlaying;

        public event EventHandler ControlClicked;

        private IMediaFile _mediaFile;
        public IMediaFile MediaFile
        {
            get => _mediaFile; 
            set
            {
                _mediaFile = value;
                SetMediaFile(value);
            }
        }

        private MouseState _mouseState = MouseState.Out;

        public int Index { get; set; }

        private void SetMediaFile(IMediaFile value)
        {
            lblTitle.Text = value.Title;
            lblPerfomerAndAlbum.Text = $@"{value.Artists} · {value.Album}";
            lblTime.Text = $@"{value.Duration.Minutes:D2}:{value.Duration.Seconds:D2}";
        }

        public UcPlaylistItem()
        {
            InitializeComponent();
            RegistMouseEvents();
        }

        private void RegistMouseEvents()
        {
            tlp.MouseEnter += Ctl_MouseEnter;
            tlp.MouseLeave += Ctl_MouseLeave;
            tlp.Click += Ctl_Click;
            foreach (Control ctl in tlp.Controls)
            {
                ctl.Click += Ctl_Click;                
            }
        }

        private void Ctl_MouseLeave(object sender, EventArgs e)
        {
            var mousePosition = PointToClient(MousePosition);
            var state = ClientRectangle.Contains(mousePosition) ? MouseState.Hover : MouseState.Out;
            SetMouseState(state);
        }        

        private void Ctl_MouseEnter(object sender, EventArgs e)
        {
            SetMouseState(MouseState.Hover);
        }

        private void SetMouseState(MouseState state)
        {
            if (_mouseState == state) return;
            _mouseState = state;
            var backColor = _mouseState == MouseState.Hover ? Color.FromArgb(51, 51, 51) : Color.Transparent;
            BackColor = backColor;
        }

        private void Ctl_Click(object sender, EventArgs e)
        {
            if (_isPlaying) return;
            SetPlaying(true);
            ControlClicked?.Invoke(this, EventArgs.Empty);
        }

        public void SetPlaying(bool isPlaying)
        {
            if (_isPlaying == isPlaying) return;
            _isPlaying = isPlaying;
            var fontColor = _isPlaying ? Color.FromArgb(255, 130, 50) : Color.White;
            lblTitle.ForeColor = lblPerfomerAndAlbum.ForeColor = lblTime.ForeColor = fontColor;
            picPlaying.Visible = isPlaying;
        }
    }
}
